package JUC.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//synchronized
public class Demo01 {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(() -> {
            phone.sms();
        }, "A").start();

        new Thread(() -> {
            phone.sms();
        }, "B").start();
    }
}

class Phone {

    Lock lock = new ReentrantLock();


    //synchronized：线程进来只会拿到一把锁
    public void sms() {

        //lock锁必须配对，否则会死锁，一个加锁配一个解锁
        lock.lock();//线程进来会拿到两把锁

        try {
            System.out.println(Thread.currentThread().getName() + "sms");
            call(); //这里还有一把锁
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


    public void call() {

        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "call");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }


}
